import axios, { Canceler, AxiosRequestConfig } from 'axios';
import Cookie from 'js-cookie';
import Vue from 'Vue';
declare const $Vue: Vue;

const server = {
  url: 'http://amazon.jiahuagame.com/amazon-console/',
  //  url: 'http://10.10.10.118:8230/amazon-console/',
  //  url: 'http://lefantian.jiahuagame.com/amazon-console/',
  // url: 'http://192.168.1.117:8230/amazon-console/',

};
if (window.location.href.match('jiahuagame')) {
  server.url = 'http://amazon.jiahuagame.com/amazon-console/';
}

if (window.location.href.match('lefantian')) {
  server.url = 'http://lefantian.jiahuagame.com/amazon-console/';
}
let cancel: Canceler;

const instance = axios.create({
  baseURL: server.url,
  timeout: 60000,
  cancelToken: new axios.CancelToken(c => {
    cancel = c;
  }),
});

instance.defaults.headers.post['Content-Type'] = 'application/json';

instance.interceptors.request.use((config: AxiosRequestConfig) => {
  
  let token = Cookie.get('p_token');
  if (token) {
    config.headers['Authorization'] = token;
  }
  return config;
}, (error: any) => {
  console.error('Request Error', error);
});


instance.interceptors.response.use(res => {
  if (res.data.result === -100) {
    Cookie.remove('p_token');
    Cookie.remove('p_userType');
    Cookie.remove('p_username');
    Cookie.remove('p_userId');
    window.location.hash = '#/';
    $Vue.$emit('snackbar', {
      text: 'Please login!'
    })
    throw new Error('');
    // window.location.reload();
  }
  return res;
}, err => {
  if (axios.isCancel(err)) {
    console.log('请求取消', err.message);
  } else {
    // TODO 判断登录状态 过期需要跳转到登录页
    console.log('请求错误', err.message);
    if (!Cookie.get('p_token')) {
      // window.location.href = '#/login'
    }
  }


  if (err.code === 'ECONNABORTED') {
    // alert('connection timeout');
  }
  return Promise.reject(err);
});

export default instance;